package com.ddxz.demo.quartz.service.impl;

import com.ddxz.demo.quartz.dto.GroupInfo;
import com.ddxz.demo.quartz.entity.GroupEntity;
import com.ddxz.demo.quartz.mapper.TaskMapper;
import com.ddxz.demo.quartz.service.QuartzService;
import com.ddxz.demo.quartz.task.ConstData;
import com.ddxz.demo.quartz.task.DdxzJobManager;
import com.ddxz.tool.core.common.CommonUtil;
import com.ddxz.tool.core.convert.BeanUtil;
import com.ddxz.tool.core.convert.StringUtil;
import com.ddxz.tool.web.dto.DdxzResponse;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * class description
 *
 * @author 朱宗刚
 * @version 1.0.0
 * @date 2020/11/24
 */

@Service
public class QuartzServiceImpl implements QuartzService, ConstData {
    /**
     * 新增/修改任务
     *
     * @param group 任务调度信息
     * @return 是否保存成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public DdxzResponse saveTask(GroupInfo group) {
        GroupEntity entity = BeanUtil.getTarget(group, GroupEntity.class);
        if(StringUtil.isEmpty(group.getId())) {
            entity.setId(CommonUtil.generatorId(TABLE_NAME));
            mapper.save(entity);
            manager.startJob(entity);
        } else {
            mapper.modify(entity);
            manager.updateJob(entity);
        }

        return DdxzResponse.correct(entity.getId());
    }

    /**
     * 移除调度任务
     *
     * @param groupId 调度标识
     * @return 是否移除成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public DdxzResponse removeTask(String groupId) {
        GroupEntity entity = mapper.getGroupById(groupId);
        mapper.remove(groupId);
        manager.removeJob(entity);

        return DdxzResponse.correct("移除成功");
    }

    /**
     * 暂停调度任务的执行
     *
     * @param groupId 调度标识
     * @return 是否暂停成功
     */
    @Override
    public DdxzResponse pauseTask(String groupId) {
        GroupEntity entity = mapper.getGroupById(groupId);
        mapper.setStatus(groupId, PAUSE);
        manager.pauseJob(entity);
        return DdxzResponse.correct("暂停成功");
    }

    /**
     * 恢复暂停的调度任务
     *
     * @param groupId 调度标识
     * @return 是否恢复成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public DdxzResponse resumeTask(String groupId) {
        GroupEntity entity = mapper.getGroupById(groupId);
        mapper.setStatus(groupId, RUNNING);
        manager.resumeJob(entity);
        return DdxzResponse.correct("恢复成功");
    }

    @Override
    public DdxzResponse onceTask(String groupId) {
        GroupEntity entity = mapper.getGroupById(groupId);
        manager.runningOnce(entity);

        return DdxzResponse.correct("执行成功");
    }

    private final TaskMapper mapper;

    private final DdxzJobManager manager;

    public QuartzServiceImpl(TaskMapper mapper, DdxzJobManager manager) {
        this.mapper = mapper;
        this.manager = manager;
    }
}
